package com.yyq.eduucenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyq.edumsm.entity.PhoneCode;
import com.yyq.edumsm.service.PhoneCodeService;
import com.yyq.edumsm.utils.HttpUtils;
import com.yyq.edumsm.utils.RandomUtils;
import com.yyq.eduucenter.entity.UcenterMember;
import com.yyq.eduucenter.entity.vo.RegisterVo;
import com.yyq.eduucenter.service.UcenterMemberService;
import com.yyq.result.JwtUtils;
import com.yyq.result.MD5;
import com.yyq.result.R;
import com.yyq.result.vo.UcenterMemberOrder;
import com.yyq.servicebase.exceptionhandler.YyqException;
import org.apache.http.HttpResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author yyq
 * @since 2021-04-27
 */
@CrossOrigin
@RestController
@RequestMapping("/eduucenter/ucenter-member")
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService service;
    @Autowired
    private PhoneCodeService phoneCodeService;

    //修改密码
    @GetMapping("changePassword/{id}/{password}/{newpassword}")
    public R changePassword(@PathVariable String id,@PathVariable String password,@PathVariable String newpassword){
        QueryWrapper<UcenterMember> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        UcenterMember one = service.getOne(wrapper);
        if(!MD5.encrypt(password).equals(one.getPassword())) throw new YyqException(20001,"原始密码错误");
        UcenterMember member=new UcenterMember();
        member.setId(id);
        member.setPassword(MD5.encrypt(newpassword));
        service.updateById(member);
        return R.ok().data("flag",1);
    }




    //登录返回token　包含头部信息　主题信息　签名
    @PostMapping("/loginPass")
    public R login(@RequestBody UcenterMember member){
        String token;
        //返回token值由Jwt生成
        token=service.loginin(member);
        return R.ok().data("token",token);
    }
    //登录返回token　包含头部信息　主题信息　签名
    @PostMapping("/login")
    public R loginPass(@RequestBody UcenterMember member){
        String token;
        //返回token值由Jwt生成
        token=service.login(member);
        return R.ok().data("token",token);

    }
    //保存用户新手机号
    @GetMapping("savePhone/{id}/{phone}/{code}")
    public R getcodeChangePhone(@PathVariable String id,@PathVariable String phone,@PathVariable String code){

        UcenterMember member=new UcenterMember();
        QueryWrapper<PhoneCode> wrapper=new QueryWrapper<>();
        wrapper.eq("mobile",phone);
        wrapper.eq("code",code);
        PhoneCode one = phoneCodeService.getOne(wrapper);
        if(one==null) throw new YyqException(20001,"验证码错误");
        member.setId(id);
        member.setMobile(phone);
        service.updateById(member);
        return R.ok().data("flag",1);

    }



    //注册获取验证码　首先不能存在该手机号
    //向数据库添加对应手机号得验证码 注册不能使用　
    @GetMapping("newCode/{phone}")
    public R getcode(@PathVariable String phone){
        //查询是否存在该用户
        QueryWrapper<UcenterMember> wrapper1=new QueryWrapper<>();
        wrapper1.eq("mobile",phone);
        UcenterMember one = service.getOne(wrapper1);
        if(one!=null) throw new YyqException(20001,"该手机号已经注册");

        //添加判断
        int flag=1;
        if(phone.length()!=11||phone==null){
            flag=0;
            throw new YyqException(20001,"手机号位数错误");
            //令flag=0代表手机号位数不

        }
        QueryWrapper<PhoneCode> wrapper=new QueryWrapper<>();
        wrapper.eq("mobile",phone);
        phoneCodeService.remove(wrapper);


        String code= RandomUtils.getFourRandomNum();
        PhoneCode phoneCode=new PhoneCode();
        phoneCode.setCode(code);
        phoneCode.setMobile(phone);
        phoneCodeService.save(phoneCode);

        //向手机发送验证码
        String host = "http://dingxin.market.alicloudapi.com";
        String path = "/dx/sendSms";
        String method = "POST";
        String appcode = "c1415493129344a2997843f4563cff83";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", "15303846538");
        querys.put("param", "code:"+code);
        querys.put("tpl_id", "TP1711063");
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok().data("flag",flag);
    }
    //注册
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo){
        registerVo.setAvatar("https://thirdwx.qlogo.cn/mmopen/vi_32/UP3ySL9icibIV9xoD0ZR9FSrF7wyagrhGItelqXibe2DxR6RQ8Kcick6IRiaMHDt5NKjVr3Pz4Z5INhhlaHgm84DKKg/132");
        boolean register = service.register(registerVo);
        int flag=0;
        if(register) flag=1;

        return R.ok().data("flag",flag);
    }

    //根据token返回用户信息
    @GetMapping("getUserInfo")
    public R getuserInfo(HttpServletRequest request)
    {
        String memberid = JwtUtils.getMemberIdByJwtToken(request);
        UcenterMember member = service.getById(memberid);

        return R.ok().data("UserInfo",member);
    }
    //为生成订单获取用户信息
    @GetMapping("getUserInfoOrder/{memberId}")
    public UcenterMemberOrder getUserInfoOrder(@PathVariable String memberId){
        UcenterMember m = service.getById(memberId);
        UcenterMemberOrder order=new UcenterMemberOrder();
        BeanUtils.copyProperties(m,order); // souce target

        return order;
    }

    //获取某天的注册人数
    @GetMapping("getRegisterNum/{day}")
    public int getRegisterNum(@PathVariable String day){
        int count=service.getCount(day);
        return count;

    }
    //更改个人信息
    @PostMapping("updateUser")
    public R updateUser(@RequestBody UcenterMember ucenterMember){
        service.updateById(ucenterMember);
        return R.ok();
    }

    //用于用户修改个人信息确保手机号为本人
    @GetMapping("changePhone/{phone}/{code}/{id}")
    public R changePhone(@PathVariable String phone,@PathVariable String code,@PathVariable String id){
        //验证手机号为本人
        QueryWrapper<UcenterMember> wrapper1=new QueryWrapper<>();
        wrapper1.eq("id",id);
        UcenterMember one1 = service.getOne(wrapper1);
        if(!one1.getMobile().equals(phone)) throw new YyqException(20001,"请输入本人手机号");
        if (phone.length()!=11) throw new YyqException(20001,"手机号位数错误");
        QueryWrapper<PhoneCode> wrapper=new QueryWrapper<>();
        wrapper.eq("mobile",phone);
        wrapper.eq("code",code);
        PhoneCode one = phoneCodeService.getOne(wrapper);
        if (one==null) throw  new YyqException(20001,"验证码错误");

        return R.ok().data("flag",1);
    }




}

